package com.ttai.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.ttai.R;
import com.ttai.dagger.componet.activity.DaggerEnterPageComponet;
import com.ttai.dagger.module.activity.EnterPagePresenterModule;
import com.ttai.presenter.activity.EnterPagePresenter;
import com.ttai.presenter.activity.InsertNewAcountPresenter;
import com.ttai.presenter.activity.InsertIdAcountPresenter;
import com.ttai.presenter.activity.InsertTipAcountPresenter;
import com.ttai.presenter.activity.LoginPresenter;
import com.ttai.presenter.activity.SRPOnePresenter;
import com.ttai.presenter.activity.SRPThreePresenter;
import com.ttai.presenter.activity.SRPTwoPresenter;
import com.ttai.ui.base.BaseActivity;
import com.ttai.untils.Constant;
import com.ttai.untils.getui.DemoIntentService;
import com.ttai.untils.getui.DemoPushService;
import com.umeng.analytics.MobclickAgent;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EnterPage extends BaseActivity {
    @Bind(R.id.et_enterphone)
    EditText etEnterphone;
    @Bind(R.id.et_entercode)
    EditText etEntercode;
    @Bind(R.id.btn_enter)
    Button btnEnter;
    @Bind(R.id.btn_enterpage)
    Button btnEnterpage;
    @Bind(R.id.btn_zhuce)
    Button btnZhuce;

    private long exitTime = 0;
    public static String enterphonenumber = "";
    public LoginPresenter loginPresenter;
    public String token;
    private static final int REQUEST_PERMISSION = 0;
    private Class userPushService = DemoPushService.class;

    public SRPOnePresenter srpOnePresenter;
    public SRPTwoPresenter srpTwoPresenter;
    public SRPThreePresenter srpThreePresenter;

    private String mac;
    private String imei;
    private String imsi;
    public static String equipmentEnvir ="";
    /**
     * dagger注入
     */
    @Inject
    EnterPagePresenter enterPagePresenter;
    /**
     * 设置计时器
     */
    private CountDownTimer timer = new CountDownTimer(30000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            btnEnter.setEnabled(false);
            btnEnter.setText("休息" + (millisUntilFinished / 1000) + "秒");
        }

        @Override
        public void onFinish() {
            btnEnter.setEnabled(true);
            btnEnter.setText("获取验证码");
        }
    };



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enterpage);

        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView barTitle = (TextView) findViewById(R.id.barTitle);
        barTitle.setText("选择我们，就是选择安全");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);


        PackageManager pkgManager = getPackageManager();

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
        }
        // 注册 intentService 后 PushDemoReceiver 无效, sdk 会使用 DemoIntentService 传递数据,
        // AndroidManifest 对应保留一个即可(如果注册 DemoIntentService, 可以去掉 PushDemoReceiver, 如果注册了
        // IntentService, 必须在 AndroidManifest 中声明)
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);

        Intent intent = new Intent(this, DemoIntentService.class);
        Intent intent1 = new Intent(this, DemoPushService.class);
        startService(intent);
        startService(intent1);

        ButterKnife.bind(this);
        setComponet();

        loginPresenter = new LoginPresenter(this);
        srpOnePresenter = new SRPOnePresenter();
        srpTwoPresenter = new SRPTwoPresenter();
        srpThreePresenter = new SRPThreePresenter();

        mac = Constant.getMacAddress();
        imei = Constant.getIMEI(this);
        imsi = Constant.getIMSI(this);
        Log.i("77", "onCreate: mac:" + mac + " imei:" + imei + " imsi:" + imsi);


    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    @Override
    public void next(View view) {

    }

    @Override
    public void pre(View view) {

    }

    @Override
    public void setComponet() {
        DaggerEnterPageComponet.builder()
                .enterPagePresenterModule(new EnterPagePresenterModule(this))
                .build()
                .in(this);

    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("登录界面"); //手动统计页面("SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this); //统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("登录界面"); //手动统计页面("SplashScreen"为页面名称，可自定义)，必须保证 onPageEnd 在 onPause 之前调用，因为SDK会在 onPause 中保存onPageEnd统计到的页面数据。
        MobclickAgent.onPause(this);
    }


    @OnClick({R.id.btn_enter, R.id.btn_enterpage, R.id.btn_zhuce})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_enter:

                try {
                    enterphonenumber = etEnterphone.getText().toString();

                    /**
                     * 判断是否为手机号
                     */

                    String mac = Constant.getMacAddress();

                    if (!Constant.isMobile(enterphonenumber)) {
                        Toast.makeText(EnterPage.this, "输入的手机号无效", Toast.LENGTH_SHORT).show();
                    } else {
                        /**
                         * 启动计时器
                         */
                        timer.start();
                    }
                    enterPagePresenter.getVerifyCode(enterphonenumber, "1");
                } catch (Exception e) {
                    Toast.makeText(EnterPage.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_enterpage:


                try {
                    enterphonenumber = etEnterphone.getText().toString();
                    equipmentEnvir = Constant.getSrpKey(enterphonenumber.substring(0, 10), imei.substring(0, 3), imsi.substring(0, 8), mac.substring(0, 1));

                    Log.i("88", "onViewClicked: equip" + equipmentEnvir + "phone" + enterphonenumber);
                    srpOnePresenter.srpOne(enterphonenumber, equipmentEnvir);

                    String scode = getScode(etEntercode.getText().toString()+enterPagePresenter.buildTime.getBuildtime());
                    String clientId = PushManager.getInstance().getClientid(EnterPage.this);
                    System.out.println("scode"+scode+" cid:"+clientId);
                    loginPresenter.getLoginInfo(enterphonenumber,scode,clientId);
                }catch (Exception e){
                    Toast.makeText(this,"请先输入以上信息",Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_zhuce:
                Intent intent = new Intent(this, Register.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 连按两次退出程序
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    private String getScode(String buildtime) {
        String scode = null;
        try {
            scode = Constant.mD5Code(buildtime);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return scode;
    }

//    public void storeNewAcount() {
//        token = Constant.getToken();
//        insertNewAcountPresenter.storeNewAcount(token);
//    }
//
//    public void storeTipAcount() {
//        token = Constant.getToken();
//        insertTipAcountPresenter.storeTipAcount(token);
//    }
//
//    public void restoreIdAcount() {
//        token = Constant.getToken();
//        insertIdAcountPresenter.storeIdAcount(token);
//    }
}
